import { Grid } from "@mui/joy";
import { Box, Button, Paper, TextField, Typography } from "@mui/material";
import {
  DatePicker,
  DateTimePicker,
  LocalizationProvider,
} from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { useMutation } from "@tanstack/react-query";
import moment from "moment/moment";
import { useSnackbar } from "notistack";
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import { useContext } from "react";
import Loading from "../../../components/loading";
import LoadingButton from "../../../components/LoadingButton";
import {
  GET_SELECT_COURSE,
  PUT_SELECT_COURSE_URL,
} from "../../../constants/url";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import { TitleContext } from "../../../router";
export default function SelectCourse() {
  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(2);
  }, []);
  const [beginTime, setBeginTime] = useState();
  const [endTime, setEndTime] = useState();
  const [name, setName] = useState();
  const { enqueueSnackbar } = useSnackbar();

  const [success, setSuccess] = useState(false);
  const { isSuccess, isError, mutate, isLoading } = useMutation(
    ["selectCourse"],
    mutateQueryFn
  );

  const submitTime = () => {
    if (!name) {
      enqueueSnackbar("请输入选课轮次", { variant: "warning" });
      return;
    }
    if (!endTime || !beginTime) {
      enqueueSnackbar("请选择开始和结束时间", { variant: "warning" });
      return;
    }
    if (endTime <= beginTime) {
      enqueueSnackbar("开始选课时间必须早于结束选课时间", {
        variant: "warning",
      });
      return;
    }
    //在这里发起修改选课时间请求
    mutate({
      url: PUT_SELECT_COURSE_URL,
      method: "put",
      data: {
        begin: beginTime,
        end: endTime,
        name: name,
      },
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      useToken: true,
    });
  };

  useEffect(() => {
    if (isSuccess) {
      setSuccess(true);
      getMutate({
        url: GET_SELECT_COURSE,
        method: "get",
        useToken: true,
      });
      setTimeout(() => setSuccess(false), 1000);
    }
  }, [isSuccess]);

  const {
    isLoading: getLoading,
    data: getData,
    isSuccess: getSuccess,
    mutate: getMutate,
  } = useMutation(["getSelectCourse"], mutateQueryFn);
  useEffect(() => {
    getMutate({
      url: GET_SELECT_COURSE,
      method: "get",
      useToken: true,
    });
  }, []);

  return (
    <div>
      <Grid container spacing={2}>
        <Grid item xs={4}>
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <Paper
              sx={{
                padding: 2,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <Typography variant="h5">选课轮次</Typography>
              <TextField
                sx={{ marginTop: 3 }}
                value={name}
                onChange={(e) => setName(e.target.value)}
                label="name"
              ></TextField>

              <Typography sx={{ marginTop: 6 }} variant="h5">
                开始选课时间
              </Typography>

              <Box sx={{ marginTop: 3 }}>
                <DateTimePicker
                  ampm={false}
                  inputFormat="YYYY-MM-DD HH:mm:ss"
                  label="Begin Time"
                  value={beginTime}
                  onChange={(newValue) => {
                    setBeginTime(
                      moment(newValue.toString()).format("YYYY-MM-DD HH:mm:ss")
                    );
                  }}
                  renderInput={(params) => <TextField {...params} />}
                />
              </Box>

              <Typography sx={{ marginTop: 6 }} variant="h5">
                结束选课时间
              </Typography>

              <Box sx={{ marginTop: 3 }}>
                <DateTimePicker
                  ampm={false}
                  inputFormat="YYYY-MM-DD HH:mm:ss"
                  label="End Time"
                  value={endTime}
                  onChange={(newValue) => {
                    setEndTime(
                      moment(newValue.toString()).format("YYYY-MM-DD HH:mm:ss")
                    );
                  }}
                  renderInput={(params) => <TextField {...params} />}
                />
              </Box>

              <Box sx={{ marginTop: 6 }}>
                <LoadingButton
                  isSuccess={success}
                  titler={success ? "添加成功" : "添加"}
                  // variant="contained"
                  isFetching={isLoading}
                  clickr={submitTime}
                />
              </Box>
            </Paper>
          </LocalizationProvider>
        </Grid>
        <Grid item xs={8}>
          <Box
            sx={{
              padding: 4,
              width: "100%",
              display: "flex",
              flexDirection: "column",
              // justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Typography variant="h4">全部轮次</Typography>
            {getLoading && <Loading />}
            {!getLoading &&
              getSuccess &&
              getData.data.data.map((val) => <ShowCard val={val} />)}
          </Box>
        </Grid>
      </Grid>
    </div>
  );
}
const ShowCard = (props) => {
  const { val } = props;
  return (
    <Paper
      elevation={3}
      sx={{
        padding: 3,
        marginTop: 3,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        width: "100%",
      }}
    >
      <Typography variant="h6" color="primary">
        {val.name}
      </Typography>
      <Typography>从</Typography>
      <Typography>
        {moment(val.begin).format("YYYY年MM月DD日HH时mm分")}
      </Typography>
      <Typography>到</Typography>
      <Typography>
        {moment(val.end).format("YYYY年MM月DD日HH时mm分")}
      </Typography>
    </Paper>
  );
};
